package com.financing.wap.weixin.handle.event;

import java.util.Date;
import java.util.List;
import java.util.Map;

import me.chanjar.weixin.mp.bean.result.WxMpUser;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.financing.wap.common.CommonConstantUtil;
import com.financing.wap.common.CommonConstantUtil.CommonStatus;
import com.financing.wap.dto.DstMemberInfoDTO;
import com.financing.wap.dto.DstUserInfoDTO;
import com.financing.wap.service.ICommonService;
import com.financing.wap.service.IDstMemberInfoService;
import com.financing.wap.service.IDstUserInfoService;
import com.financing.wap.service.weixin.service.WeixinService;
import com.financing.wap.util.DateUtil;
import com.financing.wap.util.EmojiFilterUtil;
import com.financing.wap.util.StringUtil;
import com.financing.wap.vo.ArticleInfoVO;
import com.financing.wap.weixin.handle.CreatePosterHandler;
import com.financing.wap.weixin.handle.EventHandler;
import com.financing.wap.weixin.resp.TextMessage;
import com.financing.wap.weixin.util.MessageUtil;

/**
* 扫描带参数二维码事件-用户已关注时的事件推送
* @author lisu
*
*/
@Service("scanEvent")
public class ScanEvent implements EventHandler{
	
	Logger logger = Logger.getLogger(getClass());

	public static final  Object b = new Object();
	
	@Autowired
	private IDstUserInfoService dstUserInfoService;
	
	
	@Autowired
	private CreatePosterHandler createPosterHandler;
	
	@Autowired
	private ICommonService commonService;
	
    @Autowired
    private WeixinService weixinJincsServiceImpl;
    
    @Autowired
    private IDstMemberInfoService dstMemberInfoService;
	
	@Override
	public String messageHandler(Map<String, String> requestMap) throws Exception {

		String fromUserName = requestMap.get("FromUserName"); // 发送方帐号（open_id）
		String toUserName = requestMap.get("ToUserName");// 公众帐号
		String eventKey=requestMap.get("EventKey");
		logger.info("eventKey:"+eventKey);
		boolean isRegister = true;// 是否注册
		synchronized (b) {
			// 新增用户
			// 用户是否存在
			DstUserInfoDTO wxUserInfo = new DstUserInfoDTO();
			wxUserInfo.setUserWechatOpenid(fromUserName);
			List<DstUserInfoDTO> queryList = dstUserInfoService
					.queryList(wxUserInfo);
			String userId = null;
			if (queryList == null || queryList.size() <= 0) {

				isRegister = false;

				// 根据openid获取用户信息
				WxMpUser mpUser = weixinJincsServiceImpl.getUserInfoForUserService(fromUserName);
				DstUserInfoDTO userInfo = new DstUserInfoDTO();
				userInfo.setUserWechatOpenid(mpUser.getOpenId());
				userInfo.setUserName(EmojiFilterUtil.filterEmoji(mpUser.getNickname()));
				userInfo.setUserWechatImage(mpUser.getHeadImgUrl());
				userInfo.setUserWechatAddress(mpUser.getProvince()+mpUser.getCity());
				
				userInfo.setFlagConcern(CommonConstantUtil.UserInfoStatus.FLAG_CONCERN_IS);// 已关注
				userInfo.setDeleteTag(CommonConstantUtil.CommonStatus.DELETE_TAG_NORMAL);// 否删除
				userInfo.setCreateDate(new Date(System.currentTimeMillis()));
				userInfo.setUpdateDate(new Date(System.currentTimeMillis()));
				userInfo.setRegisterDate(DateUtil.getString(
						userInfo.getCreateDate(), "yyyy-MM-dd"));
				userInfo.setCreateBy("system");
				userInfo.setUpdateBy("system");

				if (StringUtils.isNotBlank(userInfo.getUserWechatOpenid())) {
					if(StringUtils.isNotBlank(eventKey)){
						userInfo.setUserParentOpenId(eventKey);
					}else{
						//关注  查询访问最后一条记录  
//						ArticleInfoVO visitArticleInfo = commonService.visitArticleInfoGetFisrt(fromUserName);
//						if(visitArticleInfo!=null&&!StringUtil.isNullOrEmptyStr(visitArticleInfo.getUserOpenid())){
//							userInfo.setUserParentOpenId(visitArticleInfo.getUserOpenid());
//						}
					}
					// 新增用户
					dstUserInfoService.insert(userInfo);
					userId = userInfo.getId().toString();
					requestMap.put("userId", userId);
				}
			} 
			else {
				DstUserInfoDTO updateBean = queryList.get(0);
				if(StringUtil.isNullOrEmptyStr(updateBean.getUserParentOpenId())&&StringUtils.isNotBlank(eventKey)){
					updateBean.setUserParentOpenId(eventKey);
				}
				updateBean
						.setFlagConcern(CommonConstantUtil.UserInfoStatus.FLAG_CONCERN_IS);// 取消关注
				updateBean.setUpdateDate(new Date(System.currentTimeMillis()));
				dstUserInfoService.update(updateBean);
				requestMap.put("userId", userId);
			}
			
			DstMemberInfoDTO dstMemberInfo=new DstMemberInfoDTO();
			dstMemberInfo.setDeleteTag(CommonStatus.DELETE_TAG_NORMAL);
			dstMemberInfo.setUserOpenid(fromUserName);
			DstMemberInfoDTO member = dstMemberInfoService.queryListGetFirst(dstMemberInfo);
			if(member.getId()==null){
				dstMemberInfoService.createMember(fromUserName);
				//TODO 邀请人不为空，判断是否邀请超过20的倍数的人数关注   %20  判断赠送
			}
			
			logger.info("messageHandler isRegister:" + isRegister);
		}

		TextMessage textMessage = new TextMessage();
		textMessage.setToUserName(fromUserName);
		textMessage.setFromUserName(toUserName);
		textMessage.setCreateTime(new Date().getTime());
		textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
		textMessage.setFuncFlag(0);
		// 由于href属性值必须用双引号引起，这与字符串本身的双引号冲突，所以要转义
		textMessage.setContent("欢迎回来");

		logger.info("messageHandler allend!!!");

		return MessageUtil.textMessageToXml(textMessage);
	}

	@Override
	public void messageSubsequentHandler(Map<String, String> requestMap) throws Exception {

		Thread.sleep(1000);
		
		 // 发送方帐号（open_id）  
        String fromUserName = requestMap.get("FromUserName"); 
        
        String userIdStr =  requestMap.get("userId");
        if(StringUtils.isBlank(userIdStr)){
        	return ;
        }
        
        String userId = userIdStr;
        String token = requestMap.get("token");
		Thread.sleep(1000);
		
		logger.info("messageSubsequentHandler  allend!!!");
		
	}

}

